﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>设备台账管理</title>
    <link rel="stylesheet" href="../../scripts/layui-v2.5.6/layui/css/layui.css">
    <script src="../../scripts/jquery-3.4.1.min.js"></script>
    <script src="../../scripts/layui-v2.5.6/layui/layui.js"></script>
</head>
<body>
<style>
    .container {
        padding: 15px;
        background-color: #f2f2f2;
    }
    .content {
        background-color: #fff;
        padding: 15px;
        border-radius: 2px;
    }
    .form-item {
        margin-bottom: 20px;
    }
    .form-label {
        width: 100px;
        line-height: 38px;
        padding-right: 10px;
        color: #333;
    }
    .form-label.required::before {
        content: "*";
        color: #FF5722;
        margin-right: 2px;
    }
    .form-input-error {
        color: #FF5722;
        font-size: 12px;
        margin-top: 5px;
        display: none;
    }
</style>

<div class="container">
    <div class="content">
        <!-- 搜索栏 -->
        <div class="layui-form" lay-filter="searchForm">
            <div class="layui-form-item">
                <div class="layui-inline">
                    <input type="text" name="searchDeviceCode" placeholder="请输入设备编码" autocomplete="off" class="layui-input" value="" id="searchDeviceCode">
                </div>
                <div class="layui-inline">
                    <input type="text" name="searchDeviceName" placeholder="请输入设备名称" autocomplete="off" class="layui-input" value="" id="searchDeviceName">
                </div>
                <div class="layui-inline">
                    <button type="button" class="layui-btn" id="searchBtn"><i class="layui-icon layui-icon-search"></i> 搜索</button>
                    <button type="button" class="layui-btn layui-btn-primary" id="resetBtn"><i class="layui-icon layui-icon-refresh"></i> 重置</button>
                </div>
            </div>
        </div>

        <!-- 按钮组 -->
        <div class="layui-btn-group" style="margin-bottom: 10px;">
            <button class="layui-btn" id="addBtn"><i class="layui-icon layui-icon-add-1"></i> 新增</button>
            <button class="layui-btn layui-btn-warm" id="editBtn"><i class="layui-icon layui-icon-edit"></i> 修改</button>
            <button class="layui-btn layui-btn-danger" id="deleteBtn"><i class="layui-icon layui-icon-delete"></i> 删除</button>
        </div>

        <!-- 数据表格 -->
        <table id="deviceTable" lay-filter="deviceTable"></table>
    </div>
</div>

<!-- 添加/编辑表单 -->
<div class="layui-form" lay-filter="deviceForm" id="deviceForm" style="display: none; padding: 20px;">
    <div class="layui-form-item">
        <label class="layui-form-label required">设备编码</label>
        <div class="layui-input-block">
            <div class="layui-input-inline" style="width: calc(100% - 90px);">
                <input type="text" name="deviceCode" required lay-verify="required" placeholder="请输入设备编码" class="layui-input">
            </div>
            <div class="layui-input-inline" style="width: 80px;">
                <input type="checkbox" name="autoGenerate" lay-skin="switch" lay-text="自动|手动" lay-filter="autoGenerate">
            </div>
            <div class="form-input-error"></div>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label required">设备名称</label>
        <div class="layui-input-block">
            <input type="text" name="deviceName" required lay-verify="required" placeholder="请输入设备名称" class="layui-input">
            <div class="form-input-error"></div>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label required">品牌</label>
        <div class="layui-input-block">
            <input type="text" name="brand" required lay-verify="required" placeholder="请输入品牌" class="layui-input">
            <div class="form-input-error"></div>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label required">规格型号</label>
        <div class="layui-input-block">
            <textarea name="specification" required lay-verify="required" placeholder="请输入规格型号" class="layui-textarea"></textarea>
            <div class="form-input-error"></div>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label required">所属车间</label>
        <div class="layui-input-block">
            <select name="workshop" required lay-verify="required">
                <option value="">请选择车间</option>
                <option value="操作车间">操作车间</option>
                <option value="洗罐生产车间">洗罐生产车间</option>
                <option value="洗罐车间">洗罐车间</option>
                <option value="焊接">焊接</option>
            </select>
            <div class="form-input-error"></div>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label required">设备状态</label>
        <div class="layui-input-block">
            <select name="status" required lay-verify="required">
                <option value="">请选择状态</option>
                <option value="正常">正常</option>
                <option value="维修中">维修中</option>
                <option value="停用">停用</option>
                <option value="报废">报废</option>
            </select>
            <div class="form-input-error"></div>
        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="saveBtn">保存</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</div>

<!-- 表格操作列模板 -->
<script type="text/html" id="tableBar">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script>
layui.use(['form', 'table', 'layer'], function(){
    var form = layui.form;
    var table = layui.table;
    var layer = layui.layer;
    var $ = layui.$;
    
    // 全局变量，用于标记当前操作是添加还是编辑
    var currentOperation = 'add'; // 'add' 或 'edit'
    var currentEditId = null; // 当前编辑的记录ID
    var currentEditRow = null; // 当前编辑的表格行对象
    
    // 自定义验证规则
    form.verify({
        required: function(value, item) {
            if(!value || value.trim() === '') {
                return '此项为必填项，不能为空';
            }
        }
    });

    // 初始化表格
    table.render({
        elem: '#deviceTable',
        url: '/Deviceledger/GetDeviceledgerModel', // 使用你的后端方法名
        method: 'get',
        request: {
            pageName: 'page',
            limitName: 'limit'
        },
        where: {},
        page: {
            curr: 1,
            limit: 10
        },
        toolbar: true,
        defaultToolbar: ['filter', 'exports', 'print'],
        parseData: function(res) {
            // 解析后端返回的数据格式 - 你的后端直接返回数组
            console.log('后端返回的数据:', res);
            if(Array.isArray(res)) {
                return {
                    "code": 0,
                    "msg": "",
                    "count": res.length,
                    "data": res
                };
            } else {
                return {
                    "code": 0,
                    "msg": "",
                    "count": res.pageCount || res.total || 0,
                    "data": res.listDate || res.data || []
                };
            }
        },
        cols: [[
            {type: 'checkbox'},
            {field: 'id', title: 'ID', width: 80, hide: true}, // 隐藏ID列，但确保数据包含ID
            {field: 'deviceCode', title: '设备编码', width: 150},
            {field: 'deviceName', title: '设备名称', width: 200},
            {field: 'brand', title: '品牌', width: 150},
            {field: 'specification', title: '规格型号', width: 200},
            {field: 'workshop', title: '所属车间', width: 150},
            {field: 'status', title: '设备状态', width: 120, templet: function(d){
                var statusMap = {
                    '正常': '<span class="layui-badge layui-bg-green">正常</span>',
                    '维修中': '<span class="layui-badge layui-bg-orange">维修中</span>',
                    '停用': '<span class="layui-badge layui-bg-gray">停用</span>',
                    '报废': '<span class="layui-badge layui-bg-red">报废</span>'
                };
                return statusMap[d.status] || '<span class="layui-badge layui-bg-gray">未知</span>';
            }},
            {field: 'createTime', title: '创建时间', width: 160},
            {title: '操作', toolbar: '#tableBar', width: 120, fixed: 'right'}
        ]],
        limits: [5, 10, 15, 20],
        limit: 10,
        response: {
            statusCode: 0 // 成功的状态码
        },
                text: {
            none: '暂无相关数据'
        }
    });

    // 自动生成设备编码开关事件
    form.on('switch(autoGenerate)', function(data){
        var $input = $('input[name="deviceCode"]');
        if(data.elem.checked){
            var loading = layer.load(1);
            
            // 临时模拟生成编码，等后端接口实现后替换
            setTimeout(function(){
                layer.close(loading);
                var timestamp = new Date().getTime();
                var code = 'DEV' + timestamp.toString().slice(-6);
                $input.val(code).attr('disabled', 'disabled');
                $input.removeAttr('lay-verify').removeAttr('lay-reqText');
                layer.msg('编码生成成功');
            }, 500);
            
            // 实际调用后端接口的代码（暂时注释）
            /*
            $.ajax({
                url: '/Deviceledger/GenerateDeviceCode',
                type: 'GET',
                success: function(res){
                    layer.close(loading);
                    if(res && res.code === 0){
                        $input.val(res.data).attr('disabled', 'disabled');
                        $input.removeAttr('lay-verify').removeAttr('lay-reqText');
                        layer.msg('编码生成成功');
                    } else {
                        layer.msg(res.msg || '生成编码失败');
                        $(data.elem).prop('checked', false);
                        form.render('checkbox');
                    }
                },
                error: function(){
                    layer.close(loading);
                    layer.msg('服务器错误');
                    $(data.elem).prop('checked', false);
                    form.render('checkbox');
                }
            });
            */
        } else {
            $input.val('').removeAttr('disabled');
            $input.attr('lay-verify', 'required');
            layer.msg('已切换到手动输入模式');
        }
    });

    // 重置按钮点击事件
    $('#resetBtn').on('click', function(){
        $('input[name="searchDeviceCode"]').val('');
        $('input[name="searchDeviceName"]').val('');
        
        var loading = layer.load(1);
        table.reload('deviceTable', {
            where: {},
            page: {
                curr: 1
            },
            done: function() {
                layer.close(loading);
                layer.msg('已重置搜索条件');
            }
        });
    });

    // 搜索框回车事件
    $('#searchDeviceCode, #searchDeviceName').on('keydown', function(e){
        if(e.keyCode === 13) { // 回车键
            $('#searchBtn').trigger('click');
        }
    });

    // 搜索按钮点击事件
    $('#searchBtn').on('click', function(){
        var deviceCode = $('input[name="searchDeviceCode"]').val().trim();
        var deviceName = $('input[name="searchDeviceName"]').val().trim();
        
        // 如果搜索条件为空，提示用户
        if(!deviceCode && !deviceName) {
            layer.msg('请输入搜索条件');
            return;
        }
        
        var whereCondition = {};
        // 参数名要匹配后端接口的参数名：code 和 name
        if(deviceCode) {
            whereCondition.code = deviceCode;
        }
        if(deviceName) {
            whereCondition.name = deviceName;
        }
        
        console.log('搜索条件:', whereCondition);
        
        var loading = layer.load(1, {
            content: '正在搜索...'
        });
        
        table.reload('deviceTable', {
            where: whereCondition,
            page: {
                curr: 1 // 重新从第一页开始
            },
            done: function(res, curr, count) {
                layer.close(loading);
                var searchText = '';
                if(deviceCode && deviceName) {
                    searchText = `设备编码"${deviceCode}"和设备名称"${deviceName}"`;
                } else if(deviceCode) {
                    searchText = `设备编码"${deviceCode}"`;
                } else if(deviceName) {
                    searchText = `设备名称"${deviceName}"`;
                }
                
                if(count > 0) {
                    layer.msg(`搜索到 ${count} 条符合条件的记录`);
                } else {
                    layer.msg(`未找到符合${searchText}的记录`, {icon: 2});
                }
            }
        });
    });

    // 添加按钮点击事件
    $('#addBtn').on('click', function(){
        currentOperation = 'add';
        currentEditId = null;
        currentEditRow = null;
        
        console.log('=== 添加操作开始 ===');
        console.log('设置操作模式为:', currentOperation);
        console.log('重置编辑ID为:', currentEditId);
        
        layer.open({
            type: 1,
            title: '添加设备',
            area: ['600px', '80%'],
            content: $('#deviceForm'),
            success: function(){
                // 重置表单
                form.val('deviceForm', {
                    deviceCode: '',
                    deviceName: '',
                    brand: '',
                    specification: '',
                    workshop: '',
                    status: '',
                    autoGenerate: false
                });
                $('input[name="deviceCode"]').removeAttr('disabled');
                $('.form-input-error').hide();
                
                // 清除所有验证状态
                $('#deviceForm').find('.layui-form-danger').removeClass('layui-form-danger');
                $('#deviceForm').find('.layui-form-select').removeClass('layui-form-danger');
                
                // 显示自动生成开关（添加模式下显示）
                $('.layui-input-inline:has(input[name="autoGenerate"])').show();
            }
        });
    });

    // 表单提交事件
    form.on('submit(saveBtn)', function(data){
        // 调试信息
        console.log('=== 表单提交调试信息 ===');
        console.log('当前操作模式:', currentOperation);
        console.log('当前编辑ID:', currentEditId);
        console.log('表单数据:', data.field);
        
        // 表单验证
        var deviceCodeInput = $('input[name="deviceCode"]');
        var deviceCode = deviceCodeInput.val();
        
        // 如果是编辑模式且设备编码输入框被禁用，确保能获取到值
        if(currentOperation === 'edit' && deviceCodeInput.is(':disabled')) {
            deviceCode = deviceCodeInput.val();
            console.log('编辑模式 - 禁用状态下的设备编码:', deviceCode);
        }
        
        // 验证设备编码（只有在添加模式的手动输入情况下才需要验证）
        var autoGenerateSwitch = $('input[name="autoGenerate"]');
        if(currentOperation === 'add' && !autoGenerateSwitch[0].checked && (!deviceCode || deviceCode.trim() === '')) {
            layer.msg('请输入设备编码或开启自动生成');
            return false;
        }
        
        // 编辑模式下必须有设备编码
        if(currentOperation === 'edit' && (!deviceCode || deviceCode.trim() === '')) {
            layer.msg('设备编码不能为空');
            return false;
        }
        
        // 验证必填字段
        var validationRules = [
            { field: 'deviceName', name: '设备名称' },
            { field: 'brand', name: '品牌' },
            { field: 'specification', name: '规格型号' },
            { field: 'workshop', name: '所属车间' },
            { field: 'status', name: '设备状态' }
        ];
        
        for(var i = 0; i < validationRules.length; i++) {
            var rule = validationRules[i];
            var value = data.field[rule.field];
            if(!value || value.trim() === '') {
                layer.msg('请填写' + rule.name);
                return false;
            }
        }
        
        // 构造DTO对象，匹配后端DeviceledgerDTO格式
        var dto = {
            deviceCode: deviceCode,
            deviceName: data.field.deviceName,
            brand: data.field.brand || '',
            specification: data.field.specification || '',
            workshop: data.field.workshop || '',
            status: data.field.status || ''
        };
        
        // 如果是编辑操作，添加ID和保持原有创建时间
        if(currentOperation === 'edit') {
            dto.id = currentEditId;
            console.log('编辑模式 - 设置ID:', dto.id);
        } else {
            dto.createTime = new Date().toISOString();
            console.log('添加模式 - 设置创建时间:', dto.createTime);
        }
        
        console.log('操作类型:', currentOperation);
        console.log('提交的数据:', dto);
        
        // 获取防伪令牌（如果页面中有的话）
        var token = $('input[name="__RequestVerificationToken"]').val();
        if(token) {
            dto.__RequestVerificationToken = token;
        }
        
        var loading = layer.load();
        var apiUrl = currentOperation === 'edit' ? '/Deviceledger/UpdateDeviceledger' : '/Deviceledger/AddDeviceledger';
        var successMsg = currentOperation === 'edit' ? '更新成功' : '添加成功';
        
        console.log('API调用信息:');
        console.log('- URL:', apiUrl);
        console.log('- 操作类型:', currentOperation);
        console.log('- 成功消息:', successMsg);
        
        // 尝试两种方式：先JSON，如果失败再用表单数据
        $.ajax({
            url: apiUrl,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(dto),
            success: function(res){
                layer.close(loading);
                console.log('服务器响应:', res);
                // 适配你的后端返回格式：成功返回数字1，失败返回0
                if(res && (res === 1 || res == "1")){
                    layer.closeAll('page');
                    layer.msg(successMsg);
                    
                    if(currentOperation === 'edit' && currentEditRow) {
                        // 编辑模式且有行对象引用，局部更新当前行数据
                        console.log('执行局部更新，保持位置不变');
                        var updatedData = {
                            id: currentEditId,
                            deviceCode: dto.deviceCode,
                            deviceName: dto.deviceName,
                            brand: dto.brand,
                            specification: dto.specification,
                            workshop: dto.workshop,
                            status: dto.status,
                            createTime: currentEditRow.data.createTime // 保持原创建时间
                        };
                        console.log('局部更新数据:', updatedData);
                        currentEditRow.update(updatedData);
                    } else {
                        // 添加模式或工具栏编辑，刷新整个表格
                        console.log('刷新整个表格');
                        table.reload('deviceTable');
                    }
                } else {
                    layer.msg('操作失败：返回结果为 ' + res);
                }
            },
            error: function(xhr, status, error){
                console.error('JSON方式失败，尝试表单数据方式:', {
                    status: xhr.status,
                    statusText: xhr.statusText,
                    responseText: xhr.responseText,
                    error: error
                });
                
                // 如果是400错误，尝试用表单数据格式重新提交
                if(xhr.status === 400) {
                    console.log('使用表单数据格式重新提交...');
                    $.ajax({
                        url: apiUrl,
                        type: 'POST',
                        data: dto, // 直接发送对象，jQuery会自动转换为表单数据
                        success: function(res){
                            layer.close(loading);
                            console.log('表单方式服务器响应:', res);
                            if(res && (res === 1 || res == "1")){
                                layer.closeAll('page');
                                layer.msg(successMsg);
                                
                                if(currentOperation === 'edit' && currentEditRow) {
                                    // 编辑模式且有行对象引用，局部更新当前行数据
                                    console.log('执行局部更新，保持位置不变');
                                    var updatedData = {
                                        id: currentEditId,
                                        deviceCode: dto.deviceCode,
                                        deviceName: dto.deviceName,
                                        brand: dto.brand,
                                        specification: dto.specification,
                                        workshop: dto.workshop,
                                        status: dto.status,
                                        createTime: currentEditRow.data.createTime // 保持原创建时间
                                    };
                                    console.log('局部更新数据:', updatedData);
                                    currentEditRow.update(updatedData);
                                } else {
                                    // 添加模式或工具栏编辑，刷新整个表格
                                    console.log('刷新整个表格');
                                    table.reload('deviceTable');
                                }
                            } else {
                                layer.msg('操作失败：返回结果为 ' + res);
                            }
                        },
                        error: function(xhr2, status2, error2){
                            layer.close(loading);
                            console.error('表单方式也失败:', {
                                status: xhr2.status,
                                responseText: xhr2.responseText
                            });
                            
                            var errorMsg = '服务器错误';
                            if(xhr2.status === 404) {
                                errorMsg = '接口不存在 (404)：请检查后端路由';
                            } else if(xhr2.status === 500) {
                                errorMsg = '服务器内部错误 (500)';
                            } else if(xhr2.responseText) {
                                try {
                                    var errorObj = JSON.parse(xhr2.responseText);
                                    errorMsg = errorObj.message || errorObj.msg || '参数验证失败';
                                } catch(e) {
                                    errorMsg = '服务器错误: ' + xhr2.status + ' - ' + xhr2.statusText;
                                }
                            }
                            layer.msg(errorMsg);
                        }
                    });
                } else {
                    layer.close(loading);
                    var errorMsg = '服务器错误';
                    if(xhr.status === 404) {
                        errorMsg = '接口不存在 (404)：请检查后端路由';
                    } else if(xhr.status === 500) {
                        errorMsg = '服务器内部错误 (500)';
                    }
                    layer.msg(errorMsg);
                }
            }
        });
        
        return false;
    });

    // 表格工具条事件
    table.on('tool(deviceTable)', function(obj){
        var data = obj.data;
        if(obj.event === 'edit'){
            currentOperation = 'edit';
            currentEditId = data.id;
            currentEditRow = obj; // 保存当前行对象引用
            
            console.log('=== 编辑操作开始 ===');
            console.log('设置操作模式为:', currentOperation);
            console.log('设置编辑ID为:', currentEditId);
            console.log('当前数据:', data);
            
            layer.open({
                type: 1,
                title: '编辑设备',
                area: ['600px', '80%'],
                content: $('#deviceForm'),
                success: function(){
                    // 填充表单数据
                    form.val('deviceForm', {
                        deviceCode: data.deviceCode,
                        deviceName: data.deviceName,
                        brand: data.brand,
                        specification: data.specification,
                        workshop: data.workshop,
                        status: data.status,
                        autoGenerate: false // 编辑模式下默认关闭自动生成
                    });
                    
                    // 编辑模式下禁用设备编码并隐藏自动生成功能
                    $('input[name="deviceCode"]').attr('disabled', 'disabled');
                    $('.layui-input-inline:has(input[name="autoGenerate"])').hide();
                    
                    // 清除验证状态
                    $('.form-input-error').hide();
                    $('#deviceForm').find('.layui-form-danger').removeClass('layui-form-danger');
                    $('#deviceForm').find('.layui-form-select').removeClass('layui-form-danger');
                    
                    console.log('编辑模式 - 当前记录ID:', currentEditId);
                    console.log('编辑模式 - 填充数据:', data);
                }
            });
        } else if(obj.event === 'del'){
            var deviceInfo = `设备编码：${data.deviceCode}<br/>设备名称：${data.deviceName}`;
            
            layer.confirm(`您确认要删除以下设备吗？<br/><br/>${deviceInfo}<br/><br/>删除后将无法恢复！`, {
                title: '删除确认',
                icon: 3,
                btn: ['确定删除', '取消'],
                btn1: function(index) {
                    console.log('=== 单个删除操作开始 ===');
                    console.log('删除设备ID:', data.id);
                    console.log('删除设备信息:', data);
                    
                    var loading = layer.load(1, {
                        content: '正在删除...'
                    });
                    
                    // 调用后端删除API
                    $.ajax({
                        url: '/Deviceledger/DeleteDeviceledger',
                        type: 'POST',
                        data: { id: data.id },
                        success: function(res){
                            layer.close(loading);
                            console.log('删除响应:', res);
                            
                            if(res && (res === 1 || res == "1")){
                                layer.close(index);
                                obj.del(); // layui表格删除行
                                layer.msg('删除成功', {icon: 1, time: 2000});
                            } else {
                                layer.msg('删除失败：返回结果为 ' + res, {icon: 2});
                            }
                        },
                        error: function(xhr, status, error){
                            layer.close(loading);
                            console.error('删除失败:', {
                                status: xhr.status,
                                responseText: xhr.responseText,
                                error: error
                            });
                            
                            var errorMsg = '删除失败';
                            if(xhr.status === 404) {
                                errorMsg = '删除接口不存在 (404)';
                            } else if(xhr.status === 500) {
                                errorMsg = '服务器内部错误 (500)';
                            } else if(xhr.responseText) {
                                try {
                                    var errorObj = JSON.parse(xhr.responseText);
                                    errorMsg = errorObj.message || errorObj.msg || '删除操作失败';
                                } catch(e) {
                                    errorMsg = '删除失败: ' + xhr.status + ' - ' + xhr.statusText;
                                }
                            }
                            layer.msg(errorMsg, {icon: 2});
                        }
                    });
                },
                btn2: function(index) {
                    layer.close(index);
                }
            });
        }
    });

    // 修改按钮点击事件
    $('#editBtn').on('click', function(){
        var checkStatus = table.checkStatus('deviceTable');
        if(checkStatus.data.length === 0){
            layer.msg('请选择要修改的记录');
            return;
        }
        if(checkStatus.data.length > 1){
            layer.msg('只能选择一条记录进行修改');
            return;
        }
        
        var data = checkStatus.data[0];
        currentOperation = 'edit';
        currentEditId = data.id;
        currentEditRow = null; // 工具栏编辑无法获取行对象，需要刷新表格
        
        console.log('=== 工具栏编辑操作开始 ===');
        console.log('设置操作模式为:', currentOperation);
        console.log('设置编辑ID为:', currentEditId);
        console.log('当前数据:', data);
        
        layer.open({
            type: 1,
            title: '修改设备',
            area: ['600px', '80%'],
            content: $('#deviceForm'),
            success: function(){
                // 填充表单数据
                form.val('deviceForm', {
                    deviceCode: data.deviceCode,
                    deviceName: data.deviceName,
                    brand: data.brand,
                    specification: data.specification,
                    workshop: data.workshop,
                    status: data.status,
                    autoGenerate: false // 编辑模式下默认关闭自动生成
                });
                
                // 编辑模式下禁用设备编码并隐藏自动生成功能
                $('input[name="deviceCode"]').attr('disabled', 'disabled');
                $('.layui-input-inline:has(input[name="autoGenerate"])').hide();
                
                // 清除验证状态
                $('.form-input-error').hide();
                $('#deviceForm').find('.layui-form-danger').removeClass('layui-form-danger');
                $('#deviceForm').find('.layui-form-select').removeClass('layui-form-danger');
                
                console.log('批量编辑模式 - 当前记录ID:', currentEditId);
                console.log('批量编辑模式 - 填充数据:', data);
            }
        });
    });

    // 批量删除按钮点击事件
    $('#deleteBtn').on('click', function(){
        var checkStatus = table.checkStatus('deviceTable');
        if(checkStatus.data.length === 0){
            layer.msg('请选择要删除的记录');
            return;
        }
        
        var deleteCount = checkStatus.data.length;
        var selectedData = checkStatus.data;
        var deviceIds = selectedData.map(function(item) { return item.id; });
        
        // 构建确认信息
        var deviceList = selectedData.map(function(item) {
            return `• ${item.deviceCode} - ${item.deviceName}`;
        }).join('<br/>');
        
        var confirmText = deleteCount === 1 ? 
            `您确认要删除以下设备吗？<br/><br/>${deviceList}<br/><br/>删除后将无法恢复！` : 
            `您确认要删除以下${deleteCount}条设备记录吗？<br/><br/>${deviceList}<br/><br/>删除后将无法恢复！`;
            
        layer.confirm(confirmText, {
            title: '批量删除确认',
            icon: 3,
            btn: ['确定删除', '取消'],
            area: ['500px', 'auto'],
            btn1: function(index) {
                console.log('=== 批量删除操作开始 ===');
                console.log('删除数量:', deleteCount);
                console.log('删除ID列表:', deviceIds);
                console.log('删除数据:', selectedData);
                
                var loading = layer.load(1, {
                    content: `正在删除${deleteCount}条记录...`
                });
                
                // 调用后端批量删除API
                $.ajax({
                    url: '/Deviceledger/DeleteDeviceledgerBatch',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(deviceIds),
                    success: function(res){
                        layer.close(loading);
                        console.log('批量删除响应:', res);
                        
                        if(res && res > 0){
                            layer.close(index);
                            layer.msg(`成功删除${res}条记录`, {icon: 1, time: 2000});
                            table.reload('deviceTable'); // 批量删除后刷新整个表格
                        } else {
                            layer.msg('删除失败：返回结果为 ' + res, {icon: 2});
                        }
                    },
                    error: function(xhr, status, error){
                        layer.close(loading);
                        console.error('批量删除失败:', {
                            status: xhr.status,
                            responseText: xhr.responseText,
                            error: error
                        });
                        
                        var errorMsg = '批量删除失败';
                        if(xhr.status === 404) {
                            errorMsg = '批量删除接口不存在 (404)';
                        } else if(xhr.status === 500) {
                            errorMsg = '服务器内部错误 (500)';
                        } else if(xhr.responseText) {
                            try {
                                var errorObj = JSON.parse(xhr.responseText);
                                errorMsg = errorObj.message || errorObj.msg || '批量删除操作失败';
                            } catch(e) {
                                errorMsg = '批量删除失败: ' + xhr.status + ' - ' + xhr.statusText;
                            }
                        }
                        layer.msg(errorMsg, {icon: 2});
                    }
                });
            },
            btn2: function(index) {
                layer.close(index);
            }
        });
    });
});
</script>
</body>
</html>